package com.example.demo.service.impl;

import com.demo.sample.common.OperationResponse;
import com.example.demo.repository.StorageRepository;
import com.example.demo.service.StorageService;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zhang
 */
@Service
@Slf4j
public class StorageServiceImpl implements StorageService {

    @Autowired
    private StorageRepository storageRepository;

    public OperationResponse deduct(String commodityCode, int count) throws Exception {
        log.info("当前 XID: {}", RootContext.getXID());

        //检查库存
        checkStorage(commodityCode,count);

        log.info("开始扣减 {} 库存", commodityCode);
        //扣减库存
        int record = storageRepository.deduct(commodityCode, count);
        log.info("扣减 {} 库存结果:{}", commodityCode, record > 0 ? "操作成功" : "扣减库存失败");

        return OperationResponse.builder()
                .success(record > 0)
                .message(record > 0 ? "操作成功" : "扣减库存失败")
                .build();
    }

    private void checkStorage(String commodityCode, int count) throws Exception {
        log.info("检查商品 {} 库存", commodityCode);
        Integer stock = storageRepository.countByCommodityCode(commodityCode);
        if (stock < count) {
            log.warn("商品{}库存不足,当前库存:{}", commodityCode, stock);
            throw new Exception("库存不足");
        }
    }
}
